﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CarController : MonoBehaviour {
	
	bool isRunning = false;
	DrawLine drawLine;
	public List<Vector3> pathPoints = new List<Vector3>();
	public List<List<Vector3>> multiPathPoints = new List<List<Vector3>>();
	private float delay = 0.5f;
	
	GameObject car;

	// Use this for initialization
	void Start () {
		drawLine = gameObject.GetComponent<DrawLine>();
		
		pathPoints.AddRange(drawLine.getListPoints);
		Debug.Log("Single: " + pathPoints.Count);
		
		multiPathPoints.AddRange(drawLine.getAllListPoints);
		Debug.Log("Multi: " + multiPathPoints.Count);
		
		car = GameObject.Find("Car");
		
		if (multiPathPoints.Count > 0)
		{
			StartCoroutine(MultiCoroutineFunction());
		}
		else 
		{
			StartCoroutine(CoroutineFunction(pathPoints));	
		}
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	IEnumerator MultiCoroutineFunction() 
	{
		int i = 0; 
		do 
		{
			yield return StartCoroutine(CoroutineFunction(multiPathPoints[i]));
			i++;
		}
		while((i < multiPathPoints.Count) && (isRunning == false));
	}
	
	IEnumerator CoroutineFunction(List<Vector3> ownPoints)
	{
		isRunning = true;
		if (ownPoints.Count > 0)
		{
			for (int index = 0; index < ownPoints.Count; index++)
			{
				//transform.Find("Car").forward
				float timeDelay = 0;
				if(index > 0)
					timeDelay = (ownPoints[index] - ownPoints[index-1]).magnitude*delay;
				
				iTween.MoveTo(car, iTween.Hash("easeType","linear","position",ownPoints[index],"time",timeDelay));
				
				if (index < ownPoints.Count - 1)
					iTween.LookTo(car, iTween.Hash("looktarget", ownPoints[index + 1], "axis", "y", "time", 0.2f));
				yield return new WaitForSeconds(timeDelay);
			}
		}
		isRunning = false;
		
	}
	
	IEnumerator DoLast() {
 
	   	while(!isRunning)       
			yield return new WaitForSeconds(0.1f);
	}
	
}
